package com.bootcamp.servlet.register;

/**
 * @program: wrok-1101
 * @description: ${description}
 * @author: Keyu Li
 * @create: 2021-11-03 15:28
 **/

import com.bootcamp.servlet.bean.UserInfoWithImg;
import com.bootcamp.servlet.util.MultiFormUserInfoUtils;
import com.bootcamp.servlet.util.UserInfoWithFileBeanHandler;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "RegisterV2Servlet", value = "/registerv2")
public class RegisterV2Servlet extends HttpServlet {
    private static final int MAX_SIZE_BYTES = 10*1024*1024;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 先判断整个请求大小不超过限额
        String length = request.getHeader("Content-Length");
        if (Integer.parseInt(length) > 2*MAX_SIZE_BYTES){
            response.setStatus(400);
            response.getWriter().println("<h1>上传文件最大10MB");
            return;
        }
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart){
            response.setStatus(500);
            response.getWriter().println("<h1>form表单设置错误，请提醒网站管理员修改！");
            return;
        }

        // 是 文件表单数据，传递给工具类，得到解析后的map
        Map userInfoMap = MultiFormUserInfoUtils.multiFormToMap(request);
        // 将map解析为对象，因为 map中value为list，所以手动解析
        UserInfoWithImg userInfo = new UserInfoWithImg();
        try {
            BeanUtils.populate(userInfo,userInfoMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
//        UserInfoWithImg userInfo = UserInfoWithFileBeanHandler.transferMapToBean(userInfoMap,UserInfoWithImg.class);
        // 将解析后的对象存入 context域中
        getServletContext().setAttribute("userInfoWithImg",userInfo);
        // 显示返回浏览的工作交给另一个servlet进行
        response.setStatus(200);
        response.setHeader("refresh","2;url="+request.getContextPath()+"/ShowRegisterInfoServlet");
        response.getWriter().println("<h1>user register succeed! please wait 2 seconds!");
    }
}
